package com.hup.utils.commons.interfaces;

import com.hup.utils.commons.annotation.BaseConstantParam;
import com.hup.utils.commons.exception.AppCommonException;

/**
 * 基础枚举类
 *
 * @author hugan
 * @date 2020/2/13
 */
@SuppressWarnings("ConstantConditions")
public interface BaseConstant {

    default int getIndex() {
        return -1;
    }

    String getDesc();

    default boolean matchDesc(String target) {
        return getDesc().equals(target);
    }

    static String[] getSelectItem(Class<? extends Enum<? extends BaseConstant>> clz) {
        Enum<? extends BaseConstant>[] enums = clz.getEnumConstants();
        String[] res = new String[enums.length];
        int i = 0;
        for (Enum<? extends BaseConstant> anEnum : enums) {
            BaseConstant baseConstant = (BaseConstant) anEnum;
            res[i] = baseConstant.getDesc();
            i++;
        }
        return res;
    }

    @SuppressWarnings("unchecked")
    static <T extends Enum<? extends BaseConstant>> T getValue(Class<T> clz, String desc) {
        Enum<? extends BaseConstant>[] enums = clz.getEnumConstants();
        for (Enum<? extends BaseConstant> anEnum : enums) {
            BaseConstant baseConstant = (BaseConstant) anEnum;
            if (baseConstant.getDesc().equals(desc)) {
                return (T) baseConstant;
            }
        }

        BaseConstantParam baseConstantParam = clz.getAnnotation(BaseConstantParam.class);
        if (baseConstantParam == null || baseConstantParam.desc() == null) {
            throw new AppCommonException("值错误:[" + desc + "]");
        } else {
            throw new AppCommonException(baseConstantParam.desc() + "错误:[" + desc + "]");
        }
    }

    static void checkItem(Class<? extends Enum<? extends BaseConstant>> clz, String desc) {
        Enum<? extends BaseConstant>[] enums = clz.getEnumConstants();
        for (Enum<? extends BaseConstant> anEnum : enums) {
            BaseConstant baseConstant = (BaseConstant) anEnum;
            if (baseConstant.getDesc().equals(desc)) {
                return;
            }
        }
        BaseConstantParam baseConstantParam = clz.getAnnotation(BaseConstantParam.class);
        if (baseConstantParam == null || baseConstantParam.desc() == null) {
            throw new AppCommonException("值错误:" + desc + "]");
        } else {
            throw new AppCommonException(baseConstantParam.desc() + "错误:[" + desc + "]");
        }
    }

}
